import axios from 'axios'
import router from '@/router'
import { Message, Loading, Notification } from 'element-ui'

let loading

const http = axios.create({
  timeout: 1000 * 30,
  withCredentials: false,
  headers: {
    // [{"":"","":""},{"":"","":""}]  "['','','','']"
    //     "[{"username":"jx"},{"username":"cc"}]
    //   "?username=jx&password=123456"
    //   "<xml><username>jx</username><password>123456</password></xml>"
    // 注意 设置这个  就代表该axios只能发送json了.不能发送form结构了  比如 ?username=jx&password=123456
    'Content-Type': 'application/json; charset=utf-8'
  }
})

// function startLoading () {
//   loading = Loading.service({
//     lock: true,
//     text: '加载中...',
//     background: 'rgba(0, 0, 0, 0.7)'
//   })
// }
// function endLoading () {
//   loading.close()
// }

/**
 * axios.interceptors
 * axios.baseUrl 根路径
 * 请求拦截
 */
http.interceptors.request.use(config => {
  let url = config.url.substr(0, 11)
  console.log(url)
  if (localStorage.getItem('token') != null) {
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token') // 请求头带上token
  }
  return config


  startLoading()
  if (localStorage.getItem('token') != null) {
    config.headers['Authorization'] = 'Bearer '+localStorage.getItem('token') // 请求头带上token
  }
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  // 应用于token续命
  // if (response.headers.token) {
  //   localStorage.setItem("token", response.headers.token)
  //   location.reload()
  // }

  // debugger
  if (response.data.code === 401) {

    Notification.error({ title: '错误', message: '登录已失效请重新登录', duration: 2500 })
    localStorage.removeItem('token')
    router.push('/index')
  }
  return response
}, error => {
  return Promise.reject(error)
})
export default http
